"""poll URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.core.files import File
from django.http import JsonResponse, HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.urls import path

users = []


def create_user(request):
    if request.method == "POST":
        try:
            usernmae = request.POST['username']
            password = request.POST['password']
            users.append((usernmae, password))
            return JsonResponse({"errcode": 0, "errmsg": "成功"})
        except Exception as e:
            return JsonResponse({"errcode": 1, "errmsg": str(e)})
    elif request.method == "GET":
        return JsonResponse({"errcode": 0, "data": [{"username": u[0], "password": u[1]} for u in users]})

def auth(request):
    try:
        username = request.GET['username']
        password = request.GET['password']
    except:
        return HttpResponseBadRequest()

    if username == "admin" and password == "123456":
        response = HttpResponse("登录成功")
        response.set_signed_cookie("is_authorized", 1)
        # response.set_cookie("is_authorized", 1)
        return response
    else:
        return HttpResponseForbidden("错误的用户名和密码")



def upload(request):
    assert isinstance(request, HttpRequest)
    # cookies = request.headers.get("Cookie", "is_authorized=0")

    print(request.get_signed_cookie("is_authorized"))
    if request.get_signed_cookie("is_authorized", "0") == "0":
    # key, value = cookies.split("=")
    # print(key, value)
    #
    # if key== 'is_authorized' and value == "0":
        return HttpResponseForbidden()

    # print(request.headers)

    if request.method == "POST":
        for f in request.FILES.keys():
            file = request.FILES[f]
            assert isinstance(file, File)
            print(file, file.name,file.file)

            with open("./FILE-" + file.name, "wb") as fp:
                for chunk in file.chunks(512):
                    fp.write(chunk)
        return HttpResponse("文件上传成功")

    return HttpResponseBadRequest()

def form_example(request):
    select_tag = """
    <!DOCTYPE html>
<html>
<body>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
  
</body>
</html>
    """
    return HttpResponse(select_tag)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/user/', create_user),
    path('auth/', auth),
    path('upload/', upload),
    path('login/', form_example)
]
